const { Transform } = require("stream");
const _ = require('lodash');
const moment = require('moment');
const utils = require('../../utils');

module.exports = function (type, copy) {
  const stream = new Transform({ objectMode: true });
  let list = [];
  let format, line, check, force, append = '';
  type = utils.parseFunction(type);
  if (type === undefined || type === '') {
    line = true;
    check = true;
    type = 2;
  } else if (_.isFunction(type)) {
    line = false;
    format = type;
    type = undefined;
  } else if (_.isString(type)) {
    line = true;
    check = true;
    force = type[0] === '!';
    append = force ? type.substr(1, type.length) : type;
    type = 2;
  } else if (type < 10) {
    line = true;
  } else {
    line = false;
    type -= 10;
  }
  stream._transform = function (chunk, encoding, callback) {
    stream.push(chunk);
    list.push(chunk);
    callback();
  };
  stream.on('finish', async function () {
    utils.debug('consoleWriter [finish]');
    if (format) {
      list = await format(list, { _, moment, utils });
      console.log(list);
      copy && utils.copy(_.isString(list) ? list : utils.stringify(list, 2));
    } else if (line) {
      const _list = [];
      for (let item of list) {
        item = ((check && _.isString(item) && !force) ? item : utils.stringify(item, type)) + append;
        console.log(item);
        _list.push(item);
      }
      copy && utils.copy(_list.join('\n'));
    } else {
      list = utils.stringify(list, type);
      console.log(list);
      copy && utils.copy(list);
    }
  });

  return stream;
};